package com.gxuwz.stats.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.ResearchProject;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.ResearchProjectService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userResearchProject")
public class ResearchProjectUserController {

    @Autowired
    private ResearchProjectService researchProjectService;
    @Autowired
    private UserService userService;

    /**
     * 分页查询
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/reProUserList")
    public ResponseEntity<Map<String, Object>> reProUserList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {
//            System.out.println("收到的查询集："+params);
            // 提取 Token
            String token = authorization.replace("Bearer ", "");
//            System.out.println("Received Token: " + token);

// 解析 Token 获取当前用户ID（假设使用 JWT）
            JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
            String userId = jwtTokenUtil.getUserIdFromToken(token); // 自定义工具类解析Token
//            System.out.println("Token解析="+userId);

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<ResearchProject> page = new Page<>(currentPage, pageSize);
            QueryWrapper<ResearchProject> queryWrapper = new QueryWrapper<>();

            // 添加当前用户ID条件
//            queryWrapper.eq("user_id", params.get("userId"));
// 强制添加当前用户ID条件
            queryWrapper.eq("user_id", userId);
            System.out.println("ccc="+params);

            // 模糊查询条件 - 项目名称
            if (params.containsKey("projectName") && params.get("projectName") != null && !params.get("projectName").isEmpty()) {
                queryWrapper.like("project_name", params.get("projectName"));
            }

            // 模糊查询条件 - 项目级别
            if (params.containsKey("projectLevel") && params.get("projectLevel") != null && !params.get("projectLevel").isEmpty()) {
                queryWrapper.like("project_level", params.get("projectLevel"));
            }

            // 模糊查询条件 - 项目类别
            if (params.containsKey("projectCategory") && params.get("projectCategory") != null && !params.get("projectCategory").isEmpty()) {
                queryWrapper.like("project_category", params.get("projectCategory"));
            }

            // 精确查询条件 - 项目状态
            if (params.containsKey("projectStatus") && params.get("projectStatus") != null && !params.get("projectStatus").isEmpty()) {
                queryWrapper.eq("project_status", params.get("projectStatus"));
            }

// 立项时间按年份查
            if (params.containsKey("projectYear") && params.get("projectYear") != null && !params.get("projectYear").isEmpty()) {
                queryWrapper.apply("YEAR(project_year) = {0}", params.get("projectYear"));
            }
// 结题时间按年份查
            if (params.containsKey("projectEndYear") && params.get("projectEndYear") != null && !params.get("projectEndYear").isEmpty()) {
                queryWrapper.apply("YEAR(project_end_year) = {0}", params.get("projectEndYear"));
            }

            // 精确查询条件 - 项目立项提交状态
            if (params.containsKey("approvalStatus") && params.get("approvalStatus") != null && !params.get("approvalStatus").isEmpty()) {
                queryWrapper.eq("approval_status", params.get("approvalStatus"));
            }

            // 精确查询条件 - 项目立项审核状态
            if (params.containsKey("approvalReviewStatus") && params.get("approvalReviewStatus") != null && !params.get("approvalReviewStatus").isEmpty()) {
                queryWrapper.eq("approval_review_status", params.get("approvalReviewStatus"));
            }

            // 精确查询条件 - 项目结题提交状态
            if (params.containsKey("conclusionStatus") && params.get("conclusionStatus") != null && !params.get("conclusionStatus").isEmpty()) {
                queryWrapper.eq("conclusion_status", params.get("conclusionStatus"));
            }

            // 精确查询条件 - 项目结题审核状态
            if (params.containsKey("conclusionReviewStatus") && params.get("conclusionReviewStatus") != null && !params.get("conclusionReviewStatus").isEmpty()) {
                queryWrapper.eq("conclusion_review_status", params.get("conclusionReviewStatus"));
            }

            // 调用 service 层的分页查询方法
            IPage<ResearchProject> resultPage = researchProjectService.getReProListWithUserInfo(page, queryWrapper);
//            IPage<ResearchProject> resultPage = researchProjectService.page(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增
     */
    @PostMapping("/addResearchProject")
    public ResponseEntity<Map<String, Object>> addResearchProject(@RequestBody ResearchProject researchProject) {
        // 创建响应 Map
        Map<String, Object> response = new HashMap<>();
        // 1. 验证 username 是否存在
        String username = researchProject.getUsername();
        if (username == null || username.isEmpty()) {
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 根据 username 查询 user_id
        String userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        System.out.println("获取到的 user_id：" + userId);

        // 3. 设置 user_id 并保存
        researchProject.setUserId(userId);

        // 1. 自动计算分值
        int baseScore = researchProjectService.getScoreByType(researchProject.getProjectCategory());
        researchProject.setProjectScore(baseScore);

        // 2. 计算总分值
        double totalScore = researchProjectService.calculateTotalScore(researchProject);
        researchProject.setProjectTotalScore(totalScore);

        researchProject.setApprovalStatus("未提交");
        researchProject.setApprovalReviewStatus("未审核");
        researchProject.setConclusionStatus("未提交");
        researchProject.setConclusionReviewStatus("未审核");

        try {
            // 保存到数据库
            researchProjectService.save(researchProject);

            // 返回成功响应
            response.put("code", 200);
            response.put("msg", "新增成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 修改
     * @param researchProject
     * @return
     */
    @PutMapping("/editResearchProject")
    public ResponseEntity<Map<String, Object>> editResearchProject(@RequestBody ResearchProject researchProject) {

        // 1. 自动计算分值
        int baseScore = researchProjectService.getScoreByType(researchProject.getProjectCategory());
        researchProject.setProjectScore(baseScore);

        // 2. 计算总分值
        double totalScore = researchProjectService.calculateTotalScore(researchProject);
        researchProject.setProjectTotalScore(totalScore);

        researchProjectService.updateById(researchProject);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除
     */
    @DeleteMapping("/delUserReProject")
    public ResponseEntity<Map<String, Object>> deleteUserReProject(@RequestBody List<Long> researchProjectIds) {
//        System.out.println("删除：" + researchProjectIds);
        researchProjectService.removeByIds(researchProjectIds);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 立项提交
     */
    @PostMapping("/submitApprovalReProject")
    public ResponseEntity<Map<String, Object>> submitApprovalResearchProject(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        System.out.println("提交立项：" + params);
        Long projectId = Long.valueOf(params.get("projectId").toString());
        ResearchProject researchProject = researchProjectService.getById(projectId);
        if (researchProject == null) {
            response.put("code", 404);
            response.put("msg", "数据不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
        researchProject.setApprovalStatus("已提交");
        researchProject.setApprovalSubmissionTime(LocalDateTime.now());
        researchProject.setApprovalReviewTime(null);
        researchProject.setApprovalReviewStatus("未审核");
        researchProjectService.updateById(researchProject);
        response.put("code", 200);
        response.put("msg", "提交成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 结题提交
     */
    @PostMapping("/submitConclusionReProject")
    public ResponseEntity<Map<String, Object>> submitConclusionResearchProject(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        Long projectId = Long.valueOf(params.get("projectId").toString());
        ResearchProject researchProject = researchProjectService.getById(projectId);
        if (researchProject == null) {
            response.put("code", 404);
            response.put("msg", "数据不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
        researchProject.setConclusionStatus("已提交");
        researchProject.setConclusionSubmissionTime(LocalDateTime.now());
        researchProject.setConclusionReviewTime(null);
        researchProject.setConclusionReviewStatus("未审核");
        researchProjectService.updateById(researchProject);
        response.put("code", 200);
        response.put("msg", "提交成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 立项撤回
     */
    @PostMapping("/revokeApprovalReProject")
    public ResponseEntity<Map<String, Object>> revokeApprovalReProject(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        Long projectId = Long.valueOf(params.get("projectId").toString());
        ResearchProject researchProject = researchProjectService.getById(projectId);
        if (researchProject == null) {
            response.put("code", 404);
            response.put("msg", "数据不存在");
            return ResponseEntity.ok(response);
        }
        // 只有审核通过/审核不通过不能撤回，其余都能撤回
        if ("审核通过".equals(researchProject.getApprovalReviewStatus()) || "审核不通过".equals(researchProject.getApprovalReviewStatus())) {
            response.put("code", 400);
            response.put("msg", "已审核，不可撤回");
            return ResponseEntity.ok(response);
        }
        researchProject.setApprovalStatus("未提交");
        researchProject.setApprovalSubmissionTime(null);
        researchProject.setApprovalReviewTime(null);
        researchProjectService.updateById(researchProject);
        response.put("code", 200);
        response.put("msg", "撤回成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 结题撤回
     */
    @PostMapping("/revokeConclusionReProject")
    public ResponseEntity<Map<String, Object>> revokeConclusionReProject(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        Long projectId = Long.valueOf(params.get("projectId").toString());
        ResearchProject researchProject = researchProjectService.getById(projectId);
        if (researchProject == null) {
            response.put("code", 404);
            response.put("msg", "数据不存在");
            return ResponseEntity.ok(response);
        }
        // 只有审核通过/审核不通过不能撤回，其余都能撤回
        if ("审核通过".equals(researchProject.getConclusionReviewStatus()) || "审核不通过".equals(researchProject.getConclusionReviewStatus())) {
            response.put("code", 400);
            response.put("msg", "已审核，不可撤回");
            return ResponseEntity.ok(response);
        }
        researchProject.setConclusionStatus("未提交");
        researchProject.setConclusionSubmissionTime(null);
        researchProjectService.updateById(researchProject);
        response.put("code", 200);
        response.put("msg", "撤回成功");
        return ResponseEntity.ok(response);
    }

    @GetMapping("/export")
    public void exportResearchProject(
            @RequestParam(value = "year", required = false) String year,
            @RequestHeader("Authorization") String authorization,
            HttpServletResponse response) throws Exception {
        // 1. 解析token获取userId
        String token = authorization.replace("Bearer ", "");
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String userId = jwtTokenUtil.getUserIdFromToken(token);

        // 2. 查找用户名
        User user = userService.getOne(new QueryWrapper<User>().eq("user_id", userId));
        String username = user != null ? user.getUsername() : "未知用户";

        // 3. 查询 ResearchProject（可按年份筛选）
        QueryWrapper<ResearchProject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId); // 只查当前用户
        if (year != null && !year.isEmpty()) {
            queryWrapper.like("project_year", year.substring(0, 4));
        }

        // 只导出立项审核通过或结题审核通过的数据
//        queryWrapper.and(qw ->
//                qw.eq("approval_review_status", "审核通过")
//                        .or()
//                        .eq("conclusion_review_status", "审核通过")
//        );

        List<ResearchProject> list = researchProjectService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (ResearchProject w : list) {
            w.setUsername(userIdNameMap.getOrDefault(w.getUserId(), ""));
        }

        // 5. 给每条数据加序号
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i + 1); // 从1开始
        }

        // 6. 生成文件名
        String now = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName = "科研项目工作量-" + username + "-" + now + ".xlsx";

        // 7. 导出
        ExcelExportUtil.export(response, list, ResearchProject.class, "科研项目工作量", fileName);
    }

//    @GetMapping("/template/research_project.xlsx")
//    public void downloadResearchProjectTemplate(HttpServletResponse response) throws IOException {
//        String fileName = "科研项目工作量模板.xlsx"; // 你想要的中文文件名
//        // 1. 设置响应头
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
//        response.setHeader("Content-Disposition",
//                "attachment; filename=\"" + fileName + "\"; filename*=UTF-8''" + encodedFileName);
//
//        // 2. 读取模板文件并写入响应
//        InputStream in = getClass().getResourceAsStream("/template/research_project.xlsx");
//        OutputStream out = response.getOutputStream();
//        byte[] buffer = new byte[1024];
//        int len;
//        while ((len = in.read(buffer)) != -1) {
//            out.write(buffer, 0, len);
//        }
//        in.close();
//        out.flush();
//        out.close();
//    }


}
